Lambda Expressions

Lambda expressions are one of the features introduced in the C# 3.0. Lambda expressions help you to ease the burden of writing verbose Anonymous Methods. Anonymous Methods is the feature in C# 2.0. The idea behind writing the anonymous methods is to write methods inline to the code without declaring a formal named method. Normally they used for small methods that don't require any reuse.
The C# compiler automatically converts a lambda expression into a form that can be
passed to a Func<T, TResult> parameter. All lambda expressions use the new lambda operator, which is =>.This operator divides a lambda expression into two parts. On the left is specified the input parameter (or parameters). On the right is one of two things: an expression or a statement block. If the right side is an expression, then an expression lambda is being created. If the right side is a block of statements, then it is a statement lambda.

In an expression lambda, the expression on the right side of the => acts on the parameter (or parameters) specified by the left side.

(param-list) => expr

In a statement lambda, the body is enclosed by braces. A statement lambda can include other C# statements, such as loops, method calls, and if statements.

Expression Lambda

To use a lambda with a delegate involves two steps. First, you must declare the delegate type itself. Second, when you declare an instance of the delegate, assign to it the lambda expression. Once this has been done, the lambda expression can be executed by calling the delegate instance.

Program on Lambda Expression to Declare a delegate

using System;
using System.Linq;
using System.Linq.Expressions;

class sample
{
static void Main(string[] args)
{
Func<int, bool> evenodd = i => (i & 1) == 1;
for (int i = 0; i < 10; i++)
{
if (evenodd (i))
Console.WriteLine(i + " is odd");
else
Console.WriteLine(i + " is even");
}

    }
}

 

Program on Lambda with delegates
using System;

delegate double Transform(double v);
delegate bool TestInts(int w, int v);
class Sample{
static void Main() {

Transform r = n => 1.0 / n;
Console.WriteLine("The reciprocal of 4 is " + r(4.0));
Console.WriteLine("The reciprocal of 10 is " + r(10.0));
Console.WriteLine();

TestInts Factor = (n, d) => n % d == 0;

Console.WriteLine("Is 3 a factor of 9? " + Factor(9, 3));
Console.WriteLine("Is 3 a factor of 10? " + Factor(10, 3));
}
}

Program on to find the string using Lambda

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> l = new List<string>();
l.Add("PrasaD");
l.Add("nag");
l.Add("mohan");
l.Add("renu");

            Console.WriteLine("Using delegate anonymous method");
string s=l.Find (delegate (string nam)
{
return nam.Equals ("nag");
});
if (s != null)
Console.WriteLine(s);
else
Console.WriteLine("No Such name found");

            Console.WriteLine("Using Lambda expressions");
string k = l.Find(n => n.Equals("PrasaD"));
if (k != null)
Console.WriteLine(k);
else
Console.WriteLine("No Such name found");

 

        }
}
}

Program to return using Lambda Function
using System;
delegate int visionDelgate();

class sample
{
static visionDelgate  put()
{
int c = 0;
return () => c++;

    }

    static void Main()
{
visionDelgate n = put();
Console.WriteLine(n());
Console.WriteLine(n());
}
}

 

Statement Lambdas

A statement lambda expands the types of operations that can be handled directly within a lambda expression. using a statement lambda, you can use loops, if statements,declare variables, and so on. A statement lambda is easy to create. Simply enclose the body of the lambda expression within braces.

Program on Statement Lambda to find the factorial value
using System;
delegate int facotial(int n);
class StatementLambdaDemo {

static void Main() {

facotial  f = n => {
int f = 1;
for(int i=1; i <= n; i++)
f = i * f;
return f;
};

Console.WriteLine("The factorial of 5 is " + f(5));
}
}

Program on Lambda Expressions to Implement Event Handlers

using System;
delegate void MyEventHandler();

class MyEvent
{
public event MyEventHandler evnt;

public void FireEvent()
{
if (evnt  != null)
evnt ();
}
}
class LambdaEventHandlers
{
static void Main()
{
MyEvent evt = new MyEvent();
int count = 0;

evt.evnt  += () => count++;
// This statement lambda displays the value of count.
// If count is greater than 3, it is reset to 0.
evt.evnt  += () =>
{
if (count > 3) count = 0;
Console.WriteLine("Count is " + count);
};

evt.FireEvent ();
evt.FireEvent();
evt.FireEvent();
evt.FireEvent();
evt.FireEvent();
}
}